//
//  MainTabBarController.m
//  MiAiApp
//
//  Created by 徐阳 on 2017/5/18.
//  Copyright © 2017年 徐阳. All rights reserved.
//

#import "MainTabBarController.h"

//#import "RootNavigationController.h"
//#import "HomeTableViewController.h"
//#import "Home1TableViewController.h"
//
//#import "PersonTableViewController.h"
//#import "ReadVideoViewController.h"
//#import "CategoryViewController.h"
//#import "UITabBar+CustomBadge.h"
//#import "XYTabBar.h"
//#import "ApplyViewController.h"
//#import "ApplyCheckApi.h"
//#import "SxyMainTableViewController.h"
//#import "XxMainViewController.h"
//#import "PersonViewController.h"
@interface MainTabBarController ()<UITabBarControllerDelegate>

@property (nonatomic,strong) NSMutableArray * VCS;//tabbar root VC

@end

@implementation MainTabBarController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(login) name:KNotificationOnKick object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeHome) name:KNotificationHome object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeCategory) name:KNotificationCategory object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeYIDU) name:KNotificationYIDU object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changePerson) name:KNotificationPerson object:nil];

    self.delegate = self;
    //初始化tabbar
    [self setUpTabBar];
    //添加子控制器
    [self setUpAllChildViewController];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self checNickName];
    });
}


#pragma mark ————— 初始化TabBar —————
-(void)setUpTabBar{
    //设置背景色 去掉分割线
//    XYTabBar *xy = [XYTabBar new];
//    [self setValue:xy forKey:@"tabBar"];
//    [xy.plusItem addTapBlock:^(UIButton *btn) {
//        UserInfo *info = GETUSERIFNO;
//        if (info) {
//            [self cheakRequest];
//        }else{
//            [self loginTip];
//        }
//        
//    }];
    [self.tabBar setBackgroundColor:[UIColor whiteColor]];
    [self.tabBar setBackgroundImage:[UIImage new]];
    self.tabBar.tintColor = [UIColor blackColor];
    //通过这两个参数来调整badge位置
    //    [self.tabBar setTabIconWidth:29];
    //    [self.tabBar setBadgeTop:9];
}

-(void)cheakRequest{

//    UserInfo *info = GETUSERIFNO;
//    if ([info.host isEqualToString:@"0"]) {
//        ApplyCheckApi *api = [ApplyCheckApi new];
//        api.params = @{@"type":@"ios",@"uid":info.uid,@"token":info.token};
//        [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
//            ResponseModel *model = api.result;
//            if (model.code == 200) {
//                /// 获取成功
//                UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Modules" bundle:nil];
//               ApplyViewController *avc = [sb instantiateViewControllerWithIdentifier:@"ApplyViewController"];
//               RootNavigationController *rnc = [[RootNavigationController alloc]initWithRootViewController:avc];
//               rnc.modalPresentationStyle = UIModalPresentationFullScreen;
//               avc.type = [model.data[@"status"] integerValue];
//                avc.errorDes = model.data[@"hfmsg"];
//                info.host = model.data[@"host"];
//                if ([info.host isEqualToString:@"1"]) {
//                    /// 开播
//                    [[UserManager sharedUserManager] saveUserInfo:info];
//                }else{
//                    [self presentViewController:rnc animated:YES completion:nil];
//                }
//            }else{
//                [kAppWindow makeToast:model.msg duration:1 position:CSToastPositionCenter];
//            }
//        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
//            [kAppWindow makeToast:@"网络异常" duration:1 position:CSToastPositionCenter];
//        }];
//    }else{
        // 开播
//        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Video" bundle:nil];
//        LivingViewController *lvc = [sb instantiateViewControllerWithIdentifier:@"LivingViewController"];
//        lvc.channelName = @"abc123";
//        lvc.videoProfile = AgoraVideoDimension640x480;
//        lvc.clientRole = AgoraClientRoleBroadcaster;
//        lvc.token = @"0065493a74327874791b2600b9cd69d4814IADJOQNY94/4cWDssz9LcPiGBLhlUHQMz4i0hcSU3oM/EFy7As8AAAAAEAAoYE0+z8JyXgEAAQDPwnJe";
//        lvc.modalPresentationStyle = UIModalPresentationFullScreen;
//        [self presentViewController:lvc animated:YES completion:nil];
//    }
    
}

#pragma mark - ——————— 初始化VC ————————
-(void)setUpAllChildViewController{
    _VCS = @[].mutableCopy;
    //    HomeViewController *homeVC = [[HomeViewController alloc]init];
    //    WaterFallListViewController *homeVC = [WaterFallListViewController new];
//    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"Modules" bundle:nil];
//    UIStoryboard *sb1 = [UIStoryboard storyboardWithName:@"Home" bundle:nil];
//    Home1TableViewController *homeVC = [sb1 instantiateViewControllerWithIdentifier:@"Home1TableViewController"];
//    [self setupChildViewController:homeVC title:@"首页" imageName:@"ic_tabbar_sy_n" seleceImageName:@"ic_tabbar_sy_c"];
//
//    SxyMainTableViewController *cvc = [sb instantiateViewControllerWithIdentifier:@"SxyMainTableViewController"];
//    [self setupChildViewController:cvc title:@"商学院" imageName:@"ic_tabbar_sxy_n" seleceImageName:@"ic_tabbar_sxy_c"];
//
//    XxMainViewController *rvc = [sb instantiateViewControllerWithIdentifier:@"XxMainViewController"];
//    [self setupChildViewController:rvc title:@"学习" imageName:@"ic_tabbar_xx_n" seleceImageName:@"ic_tabbar_xx_c"];
//
//    PersonViewController *pvc = [sb instantiateViewControllerWithIdentifier:@"PersonViewController"];
//    [self setupChildViewController:pvc title:@"我的" imageName:@"ic_tabbar_wd_n" seleceImageName:@"ic_tabbar_wd_c"];
//    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//
//    delegate.xxVC = rvc;

    self.viewControllers = _VCS;
}

-(void)setupChildViewController:(UIViewController*)controller title:(NSString *)title imageName:(NSString *)imageName seleceImageName:(NSString *)selectImageName{
    controller.title = title;
    controller.tabBarItem.title = title;//跟上面一样效果
    controller.tabBarItem.image = [[UIImage imageNamed:imageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    controller.tabBarItem.selectedImage = [[UIImage imageNamed:selectImageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    //未选中字体颜色
    //    [controller.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName:KBlackColor,NSFontAttributeName:Font11} forState:UIControlStateNormal];
    
    //选中字体颜色
    //    [controller.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName:PrimaryColor,NSFontAttributeName:Font11} forState:UIControlStateSelected];
    //包装导航控制器
    RootNavigationController *nav = [[RootNavigationController alloc]initWithRootViewController:controller];
    
    //    [self addChildViewController:nav];
    [_VCS addObject:nav];
    
}

#pragma mark- 检测昵称是否完整
-(void)checNickName{
//    UserInfo *userInfo = GETUSERIFNO;
//    if (userInfo) {
//        if ([[CheckOutManager sharedCheckOutManager] isBlankString:userInfo.penname]) {
//            /// 昵称不完整
//            /**
//                                    uid    是    int    用户id
//                                    token    是    string    移动端使用的秘钥
//                                    type    是    string    登录类型,ios,Android,pc,wap,wx
//                                    userdata    是    json    例：{“penname”:”输入的昵称”}
//             */
//            WEAKSELF(weakSelf);
//            __weak PopControllerManager *manager = [PopControllerManager shareManager];
//            EditNickNameView *editView = [[[NSBundle mainBundle]loadNibNamed:@"EditNickNameView" owner:nil options:nil] lastObject];
//            WEAK_VAR_VARNAME(editView, weakEditView);
//            editView.editBlock = ^{
//                EditNickNameApi *api = [EditNickNameApi new];
//                NSDictionary *dic = @{@"penname":weakEditView.nickNameTF.text};
//                api.isOpenAES = YES;
//                NSString *udata =  [dic jsonStringEncoded];
//                [SVProgressHUD showWithStatus:@"修改中..."];
//                api.params = @{@"uid":userInfo.uid,@"token":userInfo.token,@"type":@"ios",@"userdata":udata};
//                [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
//                    ResponseModel *responseModel = api.result;
//                    if (responseModel.code == 200) {
//                        [SVProgressHUD showSuccessWithStatus:@"修改成功"];
//                        [SVProgressHUD dismissWithDelay:1];
//                        userInfo.penname = weakEditView.nickNameTF.text;
//                        [[UserManager sharedUserManager] saveUserInfo:userInfo];
//                        [manager.controller dismiss];
//                    }else{
//                        [SVProgressHUD dismiss];
//                        [weakEditView makeToast:responseModel.msg duration:1.5 position:CSToastPositionCenter];
//                    }
//                } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
//                    [SVProgressHUD dismiss];
//                    [weakEditView makeToast:@"网络异常" duration:1 position:CSToastPositionCenter];
//                }];
//            };
//            editView.size = CGSizeMake((SCREEN_WIDTH-40), (SCREEN_WIDTH-40)*1.15);
//            [editView.nickNameTF becomeFirstResponder];
//            [manager showViewWithType:zhPopupLayoutTypeCenter withMaskType:zhPopupMaskTypeBlackOpacity withSlideStyle:zhPopupSlideStyleFade withTouchDismiss:NO withKeyBoard:YES withView:editView];
//        }
//    }
}


-(BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
    [self checNickName];

//    UserInfo *userInfo = GETUSERIFNO;
//    BOOL isLogin = YES;
//    if (!userInfo) {
//        isLogin = NO;
//    }
//
//    if(viewController == [tabBarController.viewControllers objectAtIndex:3]||viewController == [tabBarController.viewControllers objectAtIndex:2]){
//        if (isLogin) {
//            return YES;
//        }else{
//            [self loginTip];
//            return NO;
//        }
//    }
    return YES;
   
}



-(void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{
    //    NSLog(@"选中 %ld",tabBarController.selectedIndex);
    
}

-(void)setRedDotWithIndex:(NSInteger)index isShow:(BOOL)isShow{
//    if (isShow) {
//        [self.tabBar setBadgeStyle:kCustomBadgeStyleRedDot value:0 atIndex:index];
//    }else{
//        [self.tabBar setBadgeStyle:kCustomBadgeStyleNone value:0 atIndex:index];
//    }
    
}

- (BOOL)shouldAutorotate {
    return [self.selectedViewController shouldAutorotate];
}
- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
    return [self.selectedViewController supportedInterfaceOrientations];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma  makr - 重新登录
-(void)login{
//    [[self window] makeToast:@"请重新登录" duration:1 position:CSToastPositionCenter];
//    [[UserManager sharedUserManager]removeUserInfo];

//    UIStoryboard *loginSB = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
//    LoginViewController *lvc = [loginSB instantiateViewControllerWithIdentifier:@"LoginViewController"];
//    RootNavigationController *rvc = [[RootNavigationController alloc]initWithRootViewController:lvc];
//    rvc.modalPresentationStyle = UIModalPresentationFullScreen;
//    [self presentViewController:rvc animated:YES completion:nil];
}

-(void)changeHome{
    self.selectedIndex = 0;
    self.tabBar.hidden = NO;

}

-(void)changeCategory{
    self.selectedIndex = 1;
    self.tabBar.hidden = NO;

}

-(void)changeYIDU{
    self.selectedIndex =2;
    self.tabBar.hidden = NO;

}

-(void)changePerson{
    self.selectedIndex = 3;
    self.tabBar.hidden = NO;

}

-(UIWindow *)window{
    if (@available(iOS 13.0,*)) {
        return [UIApplication sharedApplication].windows[0];
    }else{
        return [UIApplication sharedApplication].keyWindow;
    }
}

-(void) loginTip{
//    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您还未登录账号" preferredStyle:UIAlertControllerStyleAlert];
//    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"去登录" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
//        UIStoryboard *loginSB = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
//
//        LoginViewController *lvc = [loginSB instantiateViewControllerWithIdentifier:@"LoginViewController"];
//        RootNavigationController *rvc = [[RootNavigationController alloc]initWithRootViewController:lvc];
//        rvc.modalPresentationStyle = UIModalPresentationFullScreen;
//        [self presentViewController:rvc animated:YES completion:nil];
//
//
//    }];
//    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"再等等" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//
//    }];
//    [alert addAction:action1];
//    [alert addAction:action2];
//    [self presentViewController:alert animated:YES completion:nil];
}

@end
